<?php
/**
 * Created by PhpStorm.
 * User: Syousoft
 * Date: 17/2/17
 * Time: 上午10:12
 */
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class MatchController extends AdminbaseController{

    protected $match_model;

    function _initialize() {
        parent::_initialize();
        $this->match_model = D("Admin/Match");
    }

    //照片墙列表
    public function index(){

        $where=array();
        $time=I("timeSelect");
        $keyword=I("keyword");
        if(!empty($time)){
            $where["time"]=$time;
        }
        if(!empty($keyword)){
            $where["name"]=array("like","%$keyword%");
        }
        $this->match_model->where($where);
        $count=$this->match_model->count();
        $page=$this->page($count,20);

        $posts=$this->match_model->where($where)->limit($page->firstRow,$page->listRows)->order("create_at DESC")->select();
        $this->assign("page",$page->show());
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("posts",$posts);

        $this->display();
    }

    //添加比赛
    public function add(){
        $name=I("name");
        $time=I("time");

        if(!empty($name) && !empty($time)){
            $data["name"]=$name;
            $data["time"]=$time;
            $data["create_at"]=date("Y-m-d h:i:s",time());
            $result=$this->match_model->add($data);
            if($result!==false){
                exit(json_encode(array("status"=>true,"message"=>"添加成功")));
            }else{
                exit(json_encode(array("status"=>false,"message"=>"添加失败")));
            }
        }else{
            $this->display();
        }
    }

    //编辑比赛
    public function edit(){
        $id=I('id');
        $name=I('name');
        $time=I('time');
        $where['id']=$id;
        if(!empty($name) && !empty($time)){
            $data['name']=$name;
            $data['time']=$time;
            $data['update_at']=date("Y-m-d h:i:s",time());
            $result=$this->match_model->where($where)->save($data);
            if($result!==false){
                exit(json_encode(array("status"=>true,"message"=>"保存成功")));
            }else{
                exit(json_encode(array("status"=>false,"message"=>"保存失败")));
            }
        }else{
            $item=$this->match_model->where($where)->find();
            $this->assign('item',$item);
            $this->display();
        }
    }

    //删除比赛
    public function delete(){
        $id=I('id');
        //查找该比赛中有无照片墙
        $count=M('photo_wall')->where("match_id=$id")->count();
        if($count>0){
            exit(json_encode(array("status"=>false,"message"=>"该比赛下有照片墙,不可删除")));
        }else{
            $result=$this->match_model->delete($id);
            if($result!==false){
                exit(json_encode(array("status"=>true,"message"=>"删除成功")));
            }else{
                exit(json_encode(array("status"=>false,"message"=>"删除失败")));
            }
        }
    }

}